/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    ListView,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';

import Navigation from "../../../custom/Navigation";
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {getSynPaysSellerAuth, SERVER_TYPE, SynpaysTeken} from "../../../httpUtils/IparNetwork";
import CommonUtils, {getFormatDate} from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import IparInput from "../../../custom/IparInput";
import ModalBottomUtils from "../../../utils/ModalBottomUtils";

const ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2,
});


export default class AddBackCardPage extends Component<> {

    constructor(props) {
        super(props);


        this.yearData = [];
        this.monthData = [];

        let year = new Date().getFullYear();


        for (let i = 0; i < 10; i++) {
            this.yearData.push((year + i) + '')
        }
        for (let i = 1; i < 13; i++) {
            this.monthData.push(getFormatDate(i + ''))
        }


        this.state = {
            userId: '',
            isDateTimePickerVisible: false,
            isDateTimePickerTypeIsYear: true,
            showLoading: false,
            holderName: '',
            cardNumber: '',
            bankName: '',
            year: '',
            month: '',
            cvv: '',
            userData: null,
        };
        this.iparNetwork = new IparNetwork()
    }

    componentWillUnmount() {
        this.iparNetwork = null;
        this.yearData = null;
        this.monthData = null;
    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                this.userInfo = JSON.parse(result);
                this.setState({
                    userId: JSON.parse(result).main_user_id,
                    userData: JSON.parse(result),
                });
            });


    }

    /*添加借记卡*/
    addCreditCard() {
        CommonUtils.showLoading();

        let data =
            {
                Country: this.userInfo.country,
                CardNumber: this.state.cardNumber,
                UserID: this.state.userId,
                CardHolderName: this.state.holderName,
                BankName: this.state.bankName,
                ExpirationYear: this.state.year.substr(-2),
                ExpirationMonth: this.state.month,
                CVV2: this.state.cvv,
            };


        this.iparNetwork.getPostJson(SERVER_TYPE.adminIpar + 'CreditCard', data)
            .then((result) => {
                CommonUtils.dismissLoading();
                console.log(result);
                if (result.code === 200) {
                    this.props.navigator.pop();
                    this.props.callback && this.props.callback('submit')
                } else {
                    DeviceEventEmitter.emit('toast', result.message)
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                console.log(error);
            });


    }


    renderRow(item, index) {
        return (<TouchableOpacity
            onPress={() => {

                if (this.state.isDateTimePickerTypeIsYear) {
                    this.setState({
                        year: item,
                        isDateTimePickerVisible: false,
                    });
                } else {
                    this.setState({
                        month: item,
                        isDateTimePickerVisible: false,
                    });
                }
            }}>
            <Text style={[{
                padding: 8,
                flex: 1,
                fontSize: 18,
                textAlign: 'center',
            }, StyleUtils.smallFont]}>{item}</Text>
        </TouchableOpacity>)
    }

    render() {
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />

                <ModalBottomUtils
                    renderRow={(rowData, a, index) => this.renderRow(rowData, index)}
                    dataSource={ds.cloneWithRows(this.state.isDateTimePickerTypeIsYear ?
                        this.yearData : this.monthData)}
                    visible={this.state.isDateTimePickerVisible}
                    requestClose={() => this.setState({isDateTimePickerVisible: false})}/>


                <KeyboardAwareScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.showLoading}
                            onRefresh={() => {
                            }}
                        />
                    }
                >
                    <View style={[StyleUtils.flex, {padding: 16}]}>
                        {ViewUtils.getTitleView(I18n.t('default.creditCard'), I18n.t('default.allDebitCard'))}

                        <IparInput
                            style={{marginTop: 16}}
                            onChangeText={(name) => {
                                this.setState({holderName: name})
                            }}
                            placeholder={I18n.t('default.cardHolName')}/>


                        <IparInput
                            style={{marginTop: 16}}
                            onChangeText={(number) => {
                                this.setState({cardNumber: number})
                            }}
                            placeholder={I18n.t('default.cardNumber')}/>


                        <IparInput
                            style={{marginTop: 16}}
                            onChangeText={(name) => {
                                this.setState({bankName: name})
                            }}
                            placeholder={I18n.t('default.bankName')}/>


                        {ViewUtils.getButtunMenu(this.state.year ? this.state.year : I18n.t('default.year'), () => {
                            this.setState({
                                isDateTimePickerVisible: true,
                                isDateTimePickerTypeIsYear: true
                            });
                        }, {marginTop: 16})}

                        {ViewUtils.getButtunMenu(this.state.month ? this.state.month : I18n.t('default.month'), () => {
                            this.setState({
                                isDateTimePickerVisible: true,
                                isDateTimePickerTypeIsYear: false
                            });
                        }, {marginTop: 16})}

                        <IparInput
                            maxLength={3}
                            style={{marginTop: 16}}
                            onChangeText={(cvv) => {
                                this.setState({cvv: cvv})
                            }}
                            placeholder={I18n.t('default.cvv')}/>


                        {ViewUtils.getButton(I18n.t('default.submit'), () => {
                            this.submitBtn()

                        }, {marginTop: 16, marginBottom: 16})}
                    </View>
                </KeyboardAwareScrollView>

            </View>)


    }

    submitBtn() {
        if (this.state.holderName.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.cardHolName'))
        } else if (this.state.cardNumber.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.cardNumber'))
        } else if (this.state.bankName.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.bankName'))
        } else if (this.state.year === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.year'))
        } else if (this.state.month === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.month'))
        } else if (this.state.cvv.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.cvv'))
        } else {
            this.addCreditCard();
        }
    }

}



